package com.lmabbe.tenant.service.impls;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmabbe.tenant.mapper.OauthClientMapper;
import com.lmabbe.tenant.objects.converter.OauthClientConverter;
import com.lmabbe.tenant.objects.dto.OauthClientDTO;
import com.lmabbe.tenant.objects.entity.OauthClient;
import com.lmabbe.tenant.objects.vo.OauthClientVO;
import com.lmabbe.tenant.service.OauthClientService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 认证客户端
 *
 * @author lmabbe
 */
@Service
@AllArgsConstructor
public class OauthClientServiceImpl extends ServiceImpl<OauthClientMapper, OauthClient>
        implements OauthClientService {

    private final OauthClientConverter oauthClientConverter;

    @Override
    public void addNewClient(OauthClientDTO dto) {
        OauthClient oauthClient = oauthClientConverter.dto2Entity(dto);
        oauthClient.setClientKey(generateNewClientKey());
        oauthClient.setClientSecret(RandomUtil.randomString(32));
        this.baseMapper.insert(oauthClient);
    }

    @Override
    public List<OauthClientVO> findTenantAllOauthClient(String tenantId) {
        return oauthClientConverter.list2Vos(baseMapper.selectList(baseMapper.createQueryWrapper().eq(OauthClient::getTenantId, tenantId)));
    }

    /**
     * 生成新的客户端key
     *
     * @return
     */
    private String generateNewClientKey() {
        String clientKey = RandomUtil.randomString(32);
        if (hasClientKey(clientKey)) {
            generateNewClientKey();
        }
        return clientKey;
    }


    /**
     * 客户端key是否存在
     *
     * @param key
     * @return
     */
    Boolean hasClientKey(String key) {
        return baseMapper.selectCount(baseMapper.createQueryWrapper().eq(OauthClient::getClientKey, key)) > 0;
    }
}
